// pages/logs/logs.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 单词
    content: null,
    // 音标
    pron: null,
    // 词性
    definition: null,
    // 读音src
    audioURL: null,
    // 记录单词的具体信息
    List: {
      id: '',
      content: '',
      pron: '',
      definition: '',
      audioURL: '',
      showNot: '',
      collected: ''
    },
    // 计数器
    count: 0,
    url: null,
    // 单词的翻译是否显示
    showNot: false,
    // 单词是否收藏
    collected: false,
    // 记录当前点击的单词
    click_word: null,
    //收藏夹
    collection: [],
    //打卡
    daka: '打卡',
    // 是否隐藏打卡的数据界面
    show_daka: true,
    // 打卡天数
    daka_day: 0,
    // 判断是否是第一次进入该界面 
    first_init: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    //wx.removeStorageSync("collection")
    var collection = wx.getStorageSync("collection")
    var first_init = wx.getStorageSync("first_init")
    var daka_day = wx.getStorageSync("daka_day")
    if (collection === '') {
      collection = []
    }
    var array = wx.getStorageSync("day_word")
    var id = wx.getStorageSync('now_num');
    var List = that.data.List
    var daka = wx.getStorageSync("daka")
    if (daka == '') {
      daka = '打卡'
    }
    this.setData({
      array: array,
      collection: collection,
      daka: daka,
      first_init: first_init,
      daka_day: daka_day,
    })

    // 将今日已学的单词的具体信息记录到数组中
    for (var i in array) {
      that.getaudiourl();
    }

  },
  // 获取单词的具体信息同时存入记录的数组List
  getaudiourl: function (e) {
    let that = this;
    var List = that.data.List
    var id = wx.getStorageSync('now_num');
    var count = that.data.count
    var record = 'List[' + count + ']'
    // 判断是否为今日学习的最后一个单词
    if (count != id) {
      var word = that.data.array[count]
      //判断是否已收藏
      var cled = false
      for (var i = 0; i < that.data.collection.length; i++) {
        if (that.data.collection[i] == word) {
          cled = true;
          break;
        }
      }

      wx.request({
        url: 'https://api.shanbay.com/bdc/search/?word=' + word,
        data: {},
        method: 'GET',
        success: function (res) {
          that.setData({
            content: res.data.data.content,
            audioURL: res.data.data.audio,
            pron: '/' + res.data.data.pronunciation + '/',
            definition: res.data.data.definition,
            [record]: {
              word: res.data.data.content,
              pron: '/' + res.data.data.pronunciation + '/',
              definition: res.data.data.definition,
              audioURL: res.data.data.audio,
              showNot: true,
              collected: cled,
              id: count * 1 - 1,
            }
          })
        }
      })
      count++;
      that.setData({
        count: count
      })
    }
  },


  // 单词发声
  read: function (e) {
    var audiourl = e.currentTarget.id;
    console.log("id=" + audiourl)
    const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = false;
    innerAudioContext.src = audiourl;
    innerAudioContext.play()
    innerAudioContext.onPlay(() => {})
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
    var definition = e.currentTarget.id;
    this.setData({
      click_word: definition
    })
  },


  show: function (e) {
    var id = e.currentTarget.id;
    var word = this.data.List
    var a = !this.data.List[id].showNot
    var chang = 'List[' + id + '].showNot'
    this.setData({
      [chang]: a
    })

  },

  collect: function (e) {
    var id = e.currentTarget.id;
    console.log("收藏" + id);
    var word = this.data.List
    var a = this.data.List[id].collected
    var b = !this.data.List[id].collected
    if (a == false && b == true) {
      this.data.collection.push(this.data.array[id])
      console.log();
      wx.setStorageSync("collection", this.data.collection)
      console.log("收藏成功");
    } else {
      for (var i = 0; i < this.data.collection.length; i++) {
        if (this.data.collection[i] == this.data.array[id]) {
          this.data.collection.splice(i, 1)
          wx.setStorageSync("collection", this.data.collection);
          break;
        }
      }
    }
    var chang = 'List[' + id + '].collected'
    this.setData({
      [chang]: b
    })
  },


  // 将缓存中的用户数据记录到数据库
  getData: function () {
    const db = wx.cloud.database();
    var collection = this.data.collection
    db.collection('userData').doc(this.data.countID).update({
      data: {
        collection: collection,
        daka: this.data.daka,
      },
    })
  },

  getmessage: function () {
    // 获取此次用户的openid
    var _openid = wx.getStorageSync("_openid");
    const db = wx.cloud.database();
    // 获取数据库中用户的信息
    const cont = db.collection('usermessage');
    cont.where({
      _openid: _openid,
    }).get({
      success: res => {
        var username = res.data[0].username;
        this.setData({
          username: username,
        })
      }
    })

    // 获取数据库中用户的应用数据
    db.collection('userData').where({
      _openid: _openid,
    }).get({
      success: res => {
        var _id = res.data[0]._id;
        this.setData({
          countID: _id,
        })
        // console.log("用户数据3:", this.data.username);
      }
    })

  },
  // 显示打卡弹窗
  show_daka: function () {
    if (this.data.first_init != 1) {
      this.setData({
        daka: '今日已经打卡',
        show_daka: false,
        daka_day: this.data.daka_day * 1 + 1,
        first_init: 1,
      })
      wx.setStorageSync("first_init", 1);
    } else {
      this.setData({
        daka: '今日已经打卡',
        show_daka: false,
      })
    }
  },
  //隐藏打卡弹窗
  hide_daka: function () {
    this.setData({
      show_daka: true,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getmessage()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.getData()
    if (this.data.first_init === 1) {
      var countID = this.data.countID;
      console.log("id--------------------", countID);
      const db = wx.cloud.database();
      db.collection('userData').doc(countID).update({
        data: {
          daka: this.data.daka,
          daka_day: this.data.daka_day,
          first_init:1,
        },
        success: res => {
          console.log('更新数据成功------------------------', res)
        },
        fail: err => {
          icon: 'none',
          wx.showToast({
            title: '更新数据失败',
          })
          console.error('[数据库] [更新记录] 失败：', err)
        }
      })
    }
    wx.setStorageSync("first_init", this.data.first_init)
    wx.setStorageSync("daka_day", this.data.daka_day)
    wx.setStorageSync("daka", this.data.daka)

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})